package org.otarriinae.security.base.utils;

import org.otarriinae.security.base.constant.StringsConstant;
import org.otarriinae.security.base.error.SecurityErrorCode;
import org.otarriinae.security.base.model.TokenUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * 安全相关工具类
 * @author Wang Chengwei
 * @since 1.0
 */
public final class SecurityUtils {

    private static final String ANONYMOUS_USER_PRINCIPAL = "anonymousUser";

    /**
     * 工具类，防止实例化
     */
    private SecurityUtils() {
    }

    /**
     * 判断是否登录，匿名用户不算登录用户
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder
                .getContext().getAuthentication();

        return authentication != null
                && authentication.isAuthenticated()
                && !ANONYMOUS_USER_PRINCIPAL.equals(authentication.getPrincipal());
    }

    /**
     * 匿名用户
     */
    @SuppressWarnings("unused")
    public static boolean isAnonymousUser() {
        Authentication authentication = SecurityContextHolder
                .getContext().getAuthentication();
        return authentication != null && ANONYMOUS_USER_PRINCIPAL.equals(authentication.getPrincipal());
    }


    /**
     * 获取用户ID
     */
    @SuppressWarnings("java:S3740")
    public static Integer getUserId() {
        TokenUserDetails user = getUserInfo();
        return user.getUserId();
    }

    /**
     * 获取用户ID
     */
    @SuppressWarnings("java:S3740")
    public static TokenUserDetails getUserInfo() {
        Authentication authentication = SecurityContextHolder
                .getContext().getAuthentication();
        if (ANONYMOUS_USER_PRINCIPAL.equals(authentication.getPrincipal())) {
            throw new org.otarriinae.security.base.error.SecurityException(SecurityErrorCode.SESSION_TIMEOUT);
        }
        TokenUserDetails user = (TokenUserDetails) authentication.getPrincipal();
        if (user == null) {
            throw new org.otarriinae.security.base.error.SecurityException(SecurityErrorCode.SESSION_TIMEOUT);
        }
        return user;
    }

    public static String getToken(HttpServletRequest request) {
        String authHeader = request.getHeader(StringsConstant.TOKEN_HEADER);
        String authToken;
        if (authHeader != null && authHeader.startsWith(StringsConstant.TOKEN_HEAD)) {
            // The part after "Bearer"
            authToken = authHeader.substring(StringsConstant.TOKEN_HEAD.length());
        } else {
            authToken = request.getParameter(StringsConstant.TOKEN_PARAMETER);
        }
        return authToken;
    }

}
